// packageH/stock/guide/guide.js
const App = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isCart: true,
    popupSpecs: false,
    showCarList: false,

    showExplainPopup: false,
    goodsList: [],
    searchGoodsList: null,
    sets: null,
    loading: false,
    isMoreData: true,
    page: 1,
    searchInputKeyword: "",
    is_retail:false,
    show_price:false,
    show_price_flag:false,
    language:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options&&options.target == 'retail'){
      wx.setNavigationBarTitle({
        title: '零售',
      });
      this.setData({
        is_retail:true,
        isCart: false,
        show_price_flag:false,
      });
    }else{
      wx.setNavigationBarTitle({
        title: '订货',
      });
      this.setData({
        is_retail:false,
        show_price_flag:true
      });
    }
    this.getGoods();

  },
  onShareAppMessage() {},
  onShareTimeline() {},
  onReady: function() {
    let language = wx.getStorageSync('langIndex');
    this.setData({ 'language': language.en});
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getGoods();
  },
  displayExplainPopup() {
    this.setData({
      showExplainPopup: true,
    });
  },
  closeExplainPopup() {
    this.setData({
      showExplainPopup: false,
    });
  },
  viewGoods(event) {
    let _url = "/packageA/detail_v2/detail_v2?id=" + event.target.dataset.id;
    if(this.data.is_retail){
      _url = _url +'&fromStock=2';
    }else{
      _url = _url +'&fromStock=1';
    }
    wx.navigateTo({ url: _url });
  },
  getGoods() {
    if (this.data.loading === true || this.data.isMoreData === false) {
      return;
    }
    wx.showLoading({
      title: "加载中",
      mask: true,
    });
    this.setData({
      loading: true,
    });
    let urlStr = App.getNetAddresss("plugin.agency.api.goods.goods-list");
    urlStr += "&page=" + this.data.page;
    urlStr += "&is_retail=" + this.data.is_retail;
    if(this.keyword) urlStr += "&goods_key=" + this.keyword;
    App._postNetWork({
      url: urlStr,
      success: ({ data: { data, result, msg } }) => {
        if (result === 0) {
          wx.hideLoading();
          wx.showToast({
            title: msg,
            success: (result) => {
              wx.redirectTo({
                url: "/packageG/member_v2/member_v2",
              });
            },
          });
          return;
        }
        const setData = {};
        if (this.data.sets === null) {
          setData["sets"] = data.set;
        }
        if (
          data.current_page === data.last_page ||
          data.data.length === 0 ||
          data.data.length < data.per_page
        ) {
          setData["isMoreData"] = false;
        }
        let goodsList = this.data.goodsList;
        goodsList.push(...data.data);
        setData["goodsList"] = goodsList;
        setData["page"] = this.data.page + 1;
        setData["loading"] = false;
        setData['show_price'] = data.show_price;

        this.setData(setData);
        this.getCartList();
        wx.hideLoading();
      },
    });
  },
  searchGoods(event) {
    const keyword = event.detail;
    this.keyword = keyword;
    this.data.loading = false;
    this.data.isMoreData = true;
    this.data.goodsList = [];
    this.data.page = 1;
    this.getGoods();
    // let searchResult = this.data.goodsList.filter((item) => {
    //   return item.title.indexOf(keyword) !== -1;
    // });
    // this.setData({
    //   searchGoodsList: searchResult,
    // });
  },
  cancelSearch(){
    this.setData({
      goodsList: null,
    });
  },

  addCart(e) {
    console.log(e.detail);
    let _data = e.detail;
    this.activity_index = _data.index;
    if (_data.isSpecs) {
      this.activity_gid = _data.id;
      this.setData({
        goodinfo: this.data.goodsList[_data.index],
        popupSpecs: true//规格商品，显示规格弹窗
      })
      return;
    }
    this.addMemberCart({
      id: _data.id,
      total: "1",
      index: _data.index
    });
  },
  addMemberCart(_data) {
    console.log('添加到购物车===========',_data)
    //添加到购物车
    if (!_data.id) return;
    let _json = {
      goods_id: _data.id,
      total: _data.total || 1,
      option_id: _data.option_id || 0
    };

    let urlStr = App.getNetAddresss("plugin.agency.api.member-cart.store");
    App._postNetWork({
      url: urlStr,
      data: _json,
      success: (resdata) => {
        let res = resdata.data;
        wx.showToast({
          icon: "none",
          title: res.msg,
          duration: 1000,
        });
        if (res.result == 1) {
          this.setData({
            popupSpecs: false,
            showgp: false,
            ['goodsList[' + _data.index + '].total']: _data.total
          });
        }
        this.getCartList();
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  getCartList() {
    //获取购物车列表
    let urlStr = App.getNetAddresss("plugin.agency.api.member-cart.index");
    App._postNetWork({
      url: urlStr,
      data: {has_retail :this.data.is_retail?1:0},
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          this.setData({
            cartList: res.data
          });
          this.setGoodTotal();
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1000,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  setGoodTotal() {
    this.data.cartsNum = 0;
    this.data.cartsTotal = 0;
    // 计算设置当前商品列表中是否有已加入购物车的数据，有则显示购物车数量
    for (let index = 0; index < this.data.cartList.length; index++) {
      this.data.cartsNum += this.data.cartList[index].total;
      for (let j = 0; j < this.data.goodsList.length; j++) {
        if (index == 0 && this.data.goodsList[j].total) {
          this.data.goodsList[j].total = 0; //初始化置0
        }
        if (this.data.cartList[index].goods_id == this.data.goodsList[j].id) {
          let _total = 0;
          if (this.data.cartList[index].option_id == 0) {
            // 无规格
            _total = this.data.cartList[index].total; //设置商品的购物车数量
            // this.data.cartsTotal += this.data.cartList[index].total * this.data.cartList[index].goods.price;
          } else {
            // 有规格
            _total = this.data.goodsList[j].total || 0;
            _total += this.data.cartList[index].total;
            // this.data.cartsTotal += this.data.cartList[index].total * this.data.cartList[index].goods_option.product_price;
          }
          this.data.goodsList[j].total = _total; //设置商品的购物车数量
          this.data.goodsList[j].card_id = this.data.cartList[index].id; //设置商品的购物车id
        }
      }

      if (this.data.cartList[index].option_id == 0) {
        this.data.cartsTotal += this.data.cartList[index].total * this.data.cartList[index].goods.price;
      } else {
        this.data.cartsTotal += this.data.cartList[index].total * this.data.cartList[index].goods_option.product_price;
      }
    }
    this.setData({
      cartsNum: this.data.cartsNum,
      goodsList: this.data.goodsList,
      cartsTotal: this.data.cartsTotal
    });
  },
  close_yz_specs_popup(e) {
    this.setData({
      popupSpecs: false,
    });
    if (e.detail.clicktype == 1) {
      //点击确认按钮
      this.addMemberCart({ id: this.activity_gid, total: e.detail.goodsCount, option_id: e.detail.optionsId||0, index: this.activity_index });
    }
  },
  openCartListPopup() {
    this.setData({
      showCarList: true
    });
  },
  toOrder() {
    //当前是否是从下单页跳转过来的
    let _cart_ids = [];
    let _cartArr = [];

    this.data.cartList.forEach(item => {
      _cart_ids.push(item.id);
    });
    _cartArr = new Set(_cart_ids);
    _cartArr = [..._cartArr]; //去重

    setTimeout(() => {
      //跳转下单页
      wx.navigateTo({
        url: '/packageD/buy/myOrder_v2/myOrder_v2?tag=-1&fromStock=1&cart_ids=' + JSON.stringify(_cartArr)
      });
    }, 80);
  },
  // 购物车列表组件里的步进器  ============  start ==================
  changeCarList(e) {
    let _total = e.detail.name == "plus" ? e.detail.total + 1 : e.detail.name == "minus" ? e.detail.total - 1 : e.detail.total;
    this.changeCart({
      cartId: e.detail.id,
      num: _total
    });
  },
  close_yz_cartList_popup() {
    this.setData({
      showCarList: false
    });
  },
  changeCart(_data) {
    // 更新购物车数量
    console.log('更新购物车数量======',_data)
    let e = _data.detail ? _data.detail : _data;
    if (!e.cartId) {
      return;
    }
    if (Number(e.num) == 0) {
      //删除购物车
      this.destroyCart(e.cartId);
      return;
    }

    let urlStr = App.getNetAddresss("plugin.agency.api.member-cart.updateNumV2");
    App._postNetWork({
      url: urlStr,
      data: {
        id: e.cartId,
        num: e.num
      },
      success: (resdata) => {
        let res = resdata.data;
        wx.showToast({
          icon: "none",
          title: res.msg,
          duration: 1000,
        });
        if (res.result == 1) {
          this.setData({
            popupSpecs: false,
            showgp: false
          });
          if (e.index) {
            this.setData({
              ['goodList[' + e.index + '].total']: e.num
            });
          }
          this.getCartList();
        }


      },
      fail: (res) => {
        console.log(res);
      },
    });

  },
  destroyCart(_id) {
    let urlStr = App.getNetAddresss("plugin.agency.api.member-cart.destroy");
    App._postNetWork({
      url: urlStr,
      data: {
        ids: _id
      },
      success: (resdata) => {
        let res = resdata.data;
        wx.showToast({
          icon: "none",
          title: res.msg,
          duration: 1000,
        });
        this.getCartList();
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  clearCart(){
    console.log(this.data.cartList)
    let destroyCarts = [];
    this.data.cartList.forEach(item => {
      destroyCarts.push(item.id);
    });
    let urlStr = App.getNetAddresss("plugin.agency.api.member-cart.destroy");
    App._getNetWork({
      url: urlStr,
      data: {
        ids: destroyCarts.toString()
      },
      success: (resdata) => {
        let res = resdata.data;
        wx.showToast({
          icon: "none",
          title: res.msg,
          duration: 1000,
        });
        if (res.result == 1) {
          this.setData({
            popupSpecs: false,
            showCarList: false,
            showgp: false,
            goodsList: [],
            cartsNum: 0,
            cartsTotal: 0,
            page: 1,
            loading: false,
            isMoreData: true,
          });
          this.getGoods();
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  }
});
